<?php
namespace app\common\bonus;

Class Xiaoshou extends Common
{
	static $bonus_name='xiaoshou';

	public function handle($data){
		$actionData = $data['action_data'];

		$operate_id = $data['operate_id'];
		$reason_time = $data['create_time'];
		$reason_day = date('Ymd',$reason_time);

		$reason_uid = $actionData['uid'];
		$score = $actionData['score'];
		// 获取用户的所有安置人
		$seters = model('member_seter')->getSetersByUid($reason_uid);

		// 获取销售补贴配置
		$bonusConfigModel = model('bonus_config');
		// 货币配置
		$coinConfig = $bonusConfigModel::bonusConfig(self::$bonus_name,'coin');
		$coinConfig = unserialize($coinConfig['config_value']);
		// 奖金配置
		$bonusConfig = $bonusConfigModel::bonusConfig(self::$bonus_name,'bonus');
		$bonusConfig = unserialize($bonusConfig['config_value']);
		$bonusConfig = array_combine(array_column($bonusConfig,'level_id'),$bonusConfig);
		// 封顶值配置
		$maxConfig = $bonusConfigModel::bonusConfig(self::$bonus_name,'max');
		$maxConfig = unserialize($maxConfig['config_value']);
		$maxConfig = array_combine(array_column($maxConfig,'level_id'),$maxConfig);

		$model = model('member');
		$model->startTrans();
		try{
			foreach($seters as $seter):
				$uid = $seter['seter_uid'];
				$level_id = $seter['seter_level'];
				// 获取该会员等级的倍数比例配置
				$config = $bonusConfig[$level_id]['ple_data'];
				$config = array_combine(array_column($config,'multiple'),$config);
				// 该会员等级的封顶值
				$max_config = $maxConfig[$level_id];
				$max = $max_config['max'];
				// 对该用户的每个安置人计算销售补贴（对碰）
				$mathScore = $this->mathScore($reason_uid,$uid,$seter['area'],$score,$level_id,$reason_time);
				// 计算比例
				$rate = $this->mathMultipleConfig($uid,$level_id,$config);
				// 计算奖金
				$bonus = $mathScore*$rate/100;
				// 比较封顶值
				$inc_result = $this->mathMax(self::$bonus_name,$uid,$bonus,$max,$reason_time);
				$inc_bonus = $inc_result['inc_bonus'];
				$inc_tip = $inc_result['tip'];
				if($inc_bonus>0){
					// 累计奖金
					$this->incTotal($inc_bonus,$uid,$reason_day,self::$bonus_name);
					// 货币分配
					$this->bonus_record($coinConfig,self::$bonus_name,$reason_uid,$uid,$inc_bonus,$reason_time,$inc_tip);
				
					// 发布管理补贴消息队列
					$actionData = [
						'uid'=>$uid,
	                    'xiaoshou_bonus'=>$inc_bonus,
	                    'reason_time' => $reason_time
					];
					model('bonus_action')->save([
		                'operate_id' => $operate_id,
		                'action_name' => 'guanli',
		                'action_data' => serialize($actionData),
		            ]);
				}
			endforeach;
			$model->commit();
		}catch(\Exception $e){
			$model->rollback();
			$this->error=$e->getMessage();
			return false;
		}
		return true;

	}


	/**
	 * AB两区对碰
	 * @param  [type] $reason_uid  [description]
	 * @param  [type] $uid         [description]
	 * @param  [type] $area        [description]
	 * @param  [type] $score       [description]
	 * @param  [type] $level_id    [description]
	 * @param  [type] $reason_time [description]
	 * @return [type]              [description]
	 */
	private function mathScore($reason_uid,$uid,$area,$score,$reason_time){
		// 查询AB区剩余业绩
		$model = model('member_area_score');
		$area_score = $model -> getAreaScoreByUid($uid);
		$area_score = array_combine(array_column($area_score,'area'),$area_score);
		// 用户$area大区加上新增业绩
		$area_score[$area]['score'] = floatval($area_score[$area]['score'])+floatval($score);
		// 两区剩余业绩进行比较
		if($area_score[1]['score']==$area_score[2]['score']&&$area_score[1]['score']!=0){
			// A区业绩与B区业绩相等且不为0
			// 剩余业绩
			$restScore[1] = 0;
			$restScore[2] = 0;
			// 待结算业绩
			$mathScore = $area_score[1]['score'];
		}else if($area_score[1]['score']>$area_score[2]['score']){
			// A区业绩大于B区
			// 剩余业绩
			$restScore[1] = $area_score[1]['score']-$area_score[2]['score'];
			$restScore[2] = 0;
			// 待结算业绩
			$mathScore = $area_score[2]['score'];
		}else if($area_score[1]['score']<$area_score[2]['score']){
			// B区业绩大于A区业绩
			// 剩余业绩
			$restScore[1] = 0;
			$restScore[2] = $area_score[2]['score']-$area_score[1]['score'];
			// 待结算业绩
			$mathScore = $area_score[1]['score'];
		}
		// 更新剩余业绩
		$model->where(['uid'=>$uid,'area'=>1])->update(['score'=>$restScore[1]]);
		$model->where(['uid'=>$uid,'area'=>2])->update(['score'=>$restScore[2]]);

		return $mathScore;
	}

	/**
	 * 获取会员等级下的倍数比率
	 * @param  [type] $uid         [description]
	 * @param  [type] $level_id    [description]
	 * @param  [type] $bonusConfig [description]
	 * @return [type]              [description]
	 */
	private function mathMultipleConfig($uid,$level_id,$bonusConfig){
		// 根据等级获取等级业绩基数
		$base_score = model('level')::levelData($level_id)['score'];
		// 计算当前会员销售补贴倍数，并获取对应比率配置
		$total_record = model('bonus_member_total')->getOneData(self::$bonus_name,$uid);
		$total = $total_record?$total_record['total']:0;

		if(!$total){
			// 如果没有总销售奖金，
			$total = 0;
			$bonusConfig=$bonusConfig[0];// 0倍
		}else{
			$multiple = ceil($total/$base_score);

			if($multiple==0){
				$bonusConfig=$bonusConfig[0];
			}else{
				// 匹配倍数配置
				$mulArr = array_keys($bonusConfig);
				
				$last_mul = 0;
				foreach($mulArr as $mul):
					if($multiple<$mul){
						$final_mul = $last_mul;
						break;
					}
					$last_mul = $mul;
				endforeach;
				if(!isset($final_mul)){
					$final_mul = $last_mul;
				}
				
				$bonusConfig = $bonusConfig[$final_mul];

			}
		}
		$rate = $bonusConfig['rate'];
		return $rate;
	}


}